package com.zcy.service.spi;

import java.util.Arrays;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.zcy.entity.BaseEntity;
import com.zcy.repository.spi.BaseDaoInf;
import com.zcy.repository.spi.IDao;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.transaction.annotation.Transactional;


public abstract class BaseService<T extends BaseEntity> implements IService<T,Long> {

	@PersistenceContext
	private EntityManager em;
	
	@Autowired
	private BaseDaoInf<T> baseDao;
	
	@Override
	public IDao<T, Long> getDao() {
		return this.baseDao;
	}
	
	@Override
	public T findOne(Long pk) {
		return getDao().findOne(pk);
	}

	@Override
	public T findOne(Specification<T> spec) {
		return getDao().findOne(spec);
	}

	@Override
	public Iterable<T> findAll() {
		return getDao().findAll();
	}

	@Override
	public Iterable<T> findAll(Iterable<Long> pks) {
		return getDao().findAll(pks);
	}

	@Override
	public Page<T> findAll(Pageable pageable) {
		return getDao().findAll(pageable);
	}

	@Override
	public Iterable<T> findAll(Sort sort) {
		return getDao().findAll(sort);
	}

	@Override
	public List<T> findAll(Specification<T> spec) {
		return getDao().findAll(spec);
	}

	@Override
	public Page<T> findAll(Specification<T> spec, Pageable pageable) {
		return getDao().findAll(spec, pageable);
	}

	@Override
	public List<T> findAll(Specification<T> spec, Sort sort) {
		return getDao().findAll(spec, sort);
	}

	@Override
	public long count() {
		return getDao().count();
	}

	@Override
	public long count(Specification<T> spec) {
		return getDao().count(spec);
	}

	@Override
	public void delete(Iterable<T> entitys) {
		getDao().delete(entitys);
	}

	@Override
	public void delete(Long pk) {
		getDao().delete(pk);
		
	}

	@Override
	public void delete(T entity) {
		getDao().delete(entity);
	}

	@Override
	public void deleteAll() {
		getDao().deleteAll();
	}

	@Override
	public T save(T entity) {
		return getDao().save(entity);
	}

	@Override
	public Iterable<T> save(Iterable<T> entitys) {
		return getDao().save(entitys);
	}
	
	@Transactional
	public void save(String entityName,Object data) {
		Session session = em.unwrap(Session.class);
		session.saveOrUpdate(entityName, data);
	}
	
	@Override
	public boolean exists(Long pk) {
		return getDao().exists(pk);
	}

	@Override
	public void delete(Long[] pks) {
		List<Long> listPks = Arrays.asList(pks);
		Iterable<T> entitys = this.findAll(listPks);
		this.delete(entitys);
	}
	
}
